package com.mall.user.services;

import com.mall.user.IUserRegister;
import com.mall.user.converter.MemberConverter;
import com.mall.user.dal.entitys.Member;
import com.mall.user.dal.entitys.UserVerify;
import com.mall.user.dal.persistence.MemberMapper;
import com.mall.user.dal.persistence.UserVerifyMapper;
import com.mall.user.dto.UserRegisterRequest;
import com.mall.user.dto.UserRegisterResponse;
import com.mall.user.dto.UserVerifyRequest;
import com.mall.user.dto.UserVerifyResponse;
import com.mall.user.utils.AESUtil;
import com.mall.user.utils.ExceptionProcessorUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

import java.sql.Timestamp;
import java.util.UUID;

/**
 * @author Liang Shunhao
 * @description: 用户注册接口实现类
 * @date 2021/9/29 9:34
 */
@Slf4j
@Component
@Service
public class UserRegisterImpl implements IUserRegister {
    @Autowired
    MemberMapper memberMapper;

    @Autowired
    MemberConverter memberConverter;

    @Autowired
    UserVerifyMapper userVerifyMapper;

    @Autowired
    JavaMailSender mailSender;


    @Override
    public UserRegisterResponse userRegister(UserRegisterRequest userRegisterRequest) {
        UserRegisterResponse response = new UserRegisterResponse();

        // 对用户密码进行加密
        AESUtil aesUtil = new AESUtil(userRegisterRequest.getUserPwd());
        String encrypt = aesUtil.encrypt();

        // 对象转换
        try {
            // 用户表插入数据
            Member member = new Member();
            member.setUsername(userRegisterRequest.getUserName());
            member.setPassword(encrypt);
            member.setEmail(userRegisterRequest.getEmail());
            member.setCreated(new Timestamp(System.currentTimeMillis()));
            member.setUpdated(new Timestamp(System.currentTimeMillis()));
            member.setIsVerified("N");
            memberMapper.insertSelective(member);

            // 用户验证表插入数据
            UserVerify userVerify = new UserVerify();
            String uuid = DigestUtils.md5DigestAsHex((member.getUsername() + member.getPassword() + UUID.randomUUID().toString()).getBytes());
            userVerify.setUuid(uuid);
            userVerify.setUsername(member.getUsername());
            userVerify.setIsExpire("N");
            userVerify.setIsVerify("N");
            userVerify.setRegisterDate(new Timestamp(System.currentTimeMillis()));
            userVerifyMapper.insertSelective(userVerify);
            // 验证邮件发送
            sendEmail(uuid, userRegisterRequest);
        } catch (Exception e) {
            log.error("UserRegisterImpl.userRegister occur Exception" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }


        return response;
    }

    @Override
    public UserVerifyResponse verify(UserVerifyRequest verifyRequest) {
        UserVerifyResponse userVerifyResponse = new UserVerifyResponse();

        // 用户激活
        Member member = new Member();
        member.setIsVerified("Y");
        Example example = new Example(Member.class);
        example.createCriteria().andEqualTo("username", verifyRequest.getUsername());
        memberMapper.updateByExampleSelective(member, example);

        UserVerify userVerify = new UserVerify();
        userVerify.setIsVerify("Y");
        Example example1 = new Example(UserVerify.class);
        example1.createCriteria().andEqualTo("username", verifyRequest.getUsername())
                .andEqualTo("uuid", verifyRequest.getUuid());
        userVerifyMapper.updateByExampleSelective(userVerify, example1);

        return null;
    }

    /**
     * 激活邮件
     */
    private void sendEmail(String uuid, UserRegisterRequest userRegisterRequest) {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setSubject("账户激活邮件");
        simpleMailMessage.setFrom("15002817926@163.com");
        simpleMailMessage.setTo(userRegisterRequest.getEmail());
        StringBuffer stringBuffer = new StringBuffer();
        // TODO 将路径写入配置文件
        stringBuffer.append("http://localhost:8080/user/verify?uuid=").append(uuid)
                .append("&username=").append(userRegisterRequest.getUserName());
        simpleMailMessage.setText(stringBuffer.toString());

        // 发送邮件
        mailSender.send(simpleMailMessage);
    }
}
